from django.http import JsonResponse
from django.shortcuts import render
from web.forms.account import ModifyModelForm
from django.views.decorators.http import require_http_methods
from web import models
from datetime import timedelta
from django.utils import timezone

def index(request):
    # 获取ID, curr_plan
    curr_plan = request.session.get('plan')
    plans = []
    # 获取套餐
    plans_store = models.Plans.objects.all().values()
    for plan in plans_store:
        m_size = plan['memory_size']
        m_size.upper()
        d_speed = plan['download_speed']
        plans.append({
            'title': plan['title'],
            'infos': [
                (m_size + '内存'),
                ('下载速度上限' + d_speed if d_speed != 'infinity' else '下载速度无限制')
            ]
        })
    plans.append({
        'title': '您的套餐',
        'infos': [
            ('当前是' + plans_store[curr_plan - 1]['title'])
        ]
    })
    return render(request, 'web/userCenter.html', {
        'form': ModifyModelForm(request),
        'plans': plans
    })

@require_http_methods(['GET'])
def getInfo(request):
    # 获取ID
    ID = request.session.get('ID')
    if ID != -1:
        # to do
        userInfo = models.User.objects.filter(ID=ID).values().first()
        if userInfo == None:
            return JsonResponse({'status': False, 'error': '查无此人'})
        return JsonResponse({'status': True, 'userInfo': userInfo})
    else:
        return JsonResponse({'status': False, 'error': '查无此人'})

@require_http_methods(['POST'])
def saveInfo(request):
    # 获取ID
    ID = request.session.get('ID')
    form = ModifyModelForm(request, data=request.POST)
    if form.is_valid():
        update_data = form.cleaned_data
        user = models.User.objects.get(ID=ID)
        user.username = update_data['username']
        user.password = update_data['password']
        user.email = update_data['email']
        user.mobile_phone = update_data['mobile_phone']
        user.save()
        return JsonResponse({'status': True})
    else:
        return JsonResponse({'status':False, 'error': form.errors})

@require_http_methods(['POST'])
def makeOrder(request):
    plans = {
        '个人免费版': 1,
        '普通畅享版': 2,
        '会员尊享版': 3
    }
    # 获取ID
    user_ID = request.session.get('ID')
    plan = plans.get(request.POST.get('plan'))
    exists = models.Transaction.objects.filter(user_ID=user_ID, plan=plan, unvalid_time__gte=timezone.now()).exists()
    if not exists:
        duration = models.Plans.objects.get(plan=plan).valid_duration
        duration = 365 if duration == '1y' else (365)*80
        models.Transaction.objects.create(user_ID=user_ID, deal_time=timezone.now(), plan=plan, unvalid_time=(timezone.now() + timedelta(duration)))
        request.session['plan'] = plan
        return JsonResponse({'status': True, 'msg': '成功购买该套餐'})
    else:
        return JsonResponse({'status': False, 'msg': '您已购买该套餐, 请勿重复购买'})